//
//  UserInfo.swift
//  LeGou
//
//  Created by lxm on 2022/8/3.
//

import UIKit

class UserInfo: ZMViewController , UITableViewDelegate, UITableViewDataSource {
    //MARK: --------------------属性--------------------
    let padding : CGFloat = 15
    
    var data : [[(title : String, subTitle : String, icon : Bool, id : Int)]] {
        get {
            guard let user = ZMAppShareData.share.userInfo.value else {return []}
            
            if AppHelper.appVerify() {
                return [
                    [(title : "头像", subTitle : user.avatar, icon : true, id : 0),
                     (title : "昵称", subTitle : user.nickname, icon : true, id : 1),
                     (title : "邀请码", subTitle : user.showId, icon : true, id : 3),
                     (title : "绑定区域", subTitle : user.area, icon : true, id : 4)]
                ]
            } else {
                return [
                    [(title : "头像", subTitle : user.avatar, icon : true, id : 0),
                     (title : "昵称", subTitle : user.nickname, icon : true, id : 1),
                     (title : "活跃度", subTitle : "\(user.totalActivity.zm.toString(keep: 4))", icon : true, id : 2),
                     (title : "邀请码", subTitle : user.showId, icon : true, id : 3),
                     (title : "绑定区域", subTitle : user.area, icon : true, id : 4)],
                    [(title : "微信号设置", subTitle : user.wechatNo, icon : true, id : 5),
                     (title : "我的导师", subTitle : user.spreadName, icon : true, id : 6)]
                ]
            }
            
            
        }
    }
    //MARK: --------------------UI控件--------------------
    let tableView = UITableView(frame: CGRect.zero, style: .plain).then { t in
        t.separatorStyle = .none
        t.estimatedSectionFooterHeight = 0.01
        t.estimatedSectionHeaderHeight = 0.01
        t.sectionFooterHeight = 0.01
        t.sectionHeaderHeight = 0.01
    }
    
    let button = ZMUtil.button(title: "退出登录", font: UIFont.systemFont(ofSize: 16, weight: .medium), color: "退出登录".zm.hex())

    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
    }
    
    //MARK: --------------------UI--------------------
    func setUI() {
        title = "个人资料"
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        
        let v = UIView()
        tableView.tableFooterView = v
        tableView.backgroundColor = "#F5F5F5".zm.hex()
        view.backgroundColor = "#F5F5F5".zm.hex()
        
        v.frame = CGRect(x: 0, y: 0, width: SCREEN_W, height: 120)
        v.backgroundColor = .clear
        
        v.addSubview(button)
        button.backgroundColor = .white
        button.layer.cornerRadius = 23
        button.snp.makeConstraints { make in
            make.height.equalTo(46)
            make.top.equalToSuperview().offset(48)
            make.right.left.equalToSuperview()
        }
        
        tableView.zm.register(nibName: "SettingCell", reuserId: "SettingCell")
        tableView.zm.register(nibName: "UserInfoAvatarCell", reuserId: "UserInfoAvatarCell")
    }
    
    func addConstraints() {
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(padding)
            make.right.equalToSuperview().offset(-padding)
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        button.rx.tap.subscribe(onNext:{ [unowned self] resp in
            // 退出登录
            ZMAlertView.show(title: "提示", content: "是否要退出登录", left: "取消", right: "确认") {
                
            } onRight: {
                LoginService.shared.loginOut()
            }

        }).disposed(by: disposeBag)
    }

    func editeInfo(pa : [String : Any]) {
        ZMToast.showActivity()
        MineAPI.editInfo(pa).rxRequestNullAble(type: Any.self).subscribe(onNext:{ [unowned self] resp in
            ZMAppShareData.share.requestUserInfo { ok in
                if ok {
                    ZMToast.hiddenActivity()
                    self.tableView.reloadData()
                }
            }
        }).disposed(by: disposeBag)
    }
    //MARK: --------------------delegate--------------------
    func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data[section].count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 16
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 && indexPath.section == 0 {
            return 68
        } else {
            return 48
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let v = UIView()
        v.backgroundColor = .red
        return v
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = data[indexPath.section][indexPath.row]
        if indexPath.row == 0 && indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "UserInfoAvatarCell") as! UserInfoAvatarCell
            cell.titleLabel.text = data.title
            cell.avatarImg.zm.setImage(urlStr: data.subTitle, placeholder: "def_user_img")
            cell.rightIcon.isHidden = !data.icon
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SettingCell") as! SettingCell
            cell.titleLabel.text = data.title
            cell.subLabel.text = data.subTitle
            cell.rightIcon.isHidden = !data.icon
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let allCount = self.data[indexPath.section].count
        let current = indexPath.row
        if allCount == 1 {
            ZMUtil.clipCircle(view: cell, Corner: [.topLeft, .topRight, .bottomLeft, .bottomRight], radius: 12)
        } else {
            if current == 0 {
                ZMUtil.clipCircle(view: cell, Corner: [.topLeft, .topRight,], radius: 12)
            } else if current == allCount - 1 {
                ZMUtil.clipCircle(view: cell, Corner: [.bottomLeft, .bottomRight], radius: 12)
            } else {
                cell.layer.mask = nil
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.section][indexPath.row]
        if item.id == 0 {
            ZMSelectImage.show(1) { photos, assets in
                ZMToast.showActivity()
                AppHelper.uploadImgs(imgs: photos).subscribe(onNext:{ [unowned self] resp in
                    if resp.code == .success {
                        self.editeInfo(pa: ["avatar" : resp.data ?? ""])
                    } else {
                        ZMToast.showToast(title: resp.message)
                    }
                }).disposed(by: self.disposeBag)
            }
        } else if item.id == 1 {
            guard let user = ZMAppShareData.share.userInfo.value else {return}
            let v = ZMUtil.loadNibViewFullScreen(nibName: EditView.self)
            v.text.text = user.nickname
            v.confirmCallBack = {[weak v, unowned self] s in
                v?.removeFromSuperview()
                self.editeInfo(pa: ["nickname" : s])
            }
            view.addSubview(v)
//            APPWindow?.addSubview(v)
        } else if item.id == 2 {
            router.push("xm://main/Mine/activity_num")
        } else if item.id == 3 {
//            router.push("xm://main/Login/invite_ode_input", context: ["type" : 1])
        } else if item.id == 4 {
//            ZMProvinceCityView.show { province, city, area in
//
//            }
        } else if item.id == 5 {
            router.push("xm://main/Mine/set_wx")
        } else if item.id == 6 {
            ZMToast.showActivity()
            MineAPI.myRecommender.rxRequest(type: [String : String].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                let json = JSON(resp)
                let avatar = json["avatar"].stringValue
                let nickname = json["nickname"].stringValue
                let wechatCode = json["wechatCode"].stringValue
                let wechatNo = json["wechatNo"].stringValue
                let v = ZMUtil.loadNibViewFullScreen(nibName: MyRecommender.self)
                APPWindow?.addSubview(v)
                if wechatNo == "" {
                    v.copyBtn.isHidden = true
                    v.wechat.isHidden = true
                } else {
                    v.wechat.text = "微信号：\(wechatNo)"
                    v.wx = wechatNo
                }
                
                if wechatCode == "" {
                    v.hideImg()
                } else {
                    v.codeImg.zm.setImage(urlStr: wechatCode)
                }
                
                v.avatar.zm.setImage(urlStr: avatar, placeholder: "def_user_img")
                v.name.text = nickname
                
            }).disposed(by: self.disposeBag)
            
        }
    }
}
